package com.diaohw.module.log.service.netty;

import com.diaohw.module.log.obj.entity.DbLog;
import com.diaohw.module.log.obj.entity.RequestLog;
import com.diaohw.module.log.service.LogStorageService;
import com.diaohw.platform.common.enums.NettyTypeEnum;
import com.diaohw.platform.common.util.JsonUtil;
import com.diaohw.platform.utility.netty.NettyServerUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

/**
 * @author 刁海文
 * @since 2024/4/17 20:48
 */

@Service
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> implements CommandLineRunner {

    @Resource
    private LogStorageService logStorageService;

    @Value("${platform.log.netty.port}")
    private int port;

    @Override
    public void run(String... args) throws Exception {
        NettyServerUtils.start(port, this);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        NettyTypeEnum.NettyBo parse = NettyTypeEnum.parse(msg);
        switch (parse.getType()) {
            case DB_LOG -> { // SQL 日志
                DbLog dbLog = JsonUtil.toBean(parse.getData(), DbLog.class);
                logStorageService.storageDBLog(dbLog);
            }
            case HTTP_LOG -> { // HTTP 日志
                RequestLog requestLog = JsonUtil.toBean(parse.getData(), RequestLog.class);
                logStorageService.storageHttpLog(requestLog);
            }
        }
    }
}
